package com.ddf.controller.user;

import java.util.Collection;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.ddf.dao.UserDao;
import com.ddf.entity.User;

@Controller
@RequestMapping("/userService")
public class UserService {
	private Logger log = LoggerFactory.getLogger(this.getClass());
	private static final String USER_LIST = "/user/userList";
	private static final String USER_INPUT = "/user/userInput";
	
	@Autowired
	private UserDao userDao;
	
	/**
	 * 每个方法执行前都会调用一次，用来保证数据不会丢失
	 * 通过modelAndMap的方式将数据放入到request域对象中
	 * @param user
	 * @param userMap
	 */
	@ModelAttribute
	public void getUser(User user, Map<String, User> userMap) {
		if(user.getId() != null) {
			userMap.put("user", userDao.getUserById(user.getId()));
		}
	}
	
	/**
	 * 通过ModelAndView的方式将user对象放入到request域对象中
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/getUserById/{id}")
	public ModelAndView getUserById(@PathVariable() Integer id) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName(USER_INPUT);
		if(id != null) {
			mv.addObject("user", userDao.getUserById(id));
		}
		return mv;
	}
	
	@RequestMapping(value="/getAllUsers", method=RequestMethod.GET)
	public String getAllUser(Map<String, Collection<User>> userMap) {
		userMap.put("users", userDao.getAllUser());
		return USER_LIST;
	}
	
	@RequestMapping(value="/addUser", method=RequestMethod.POST)
	public String addUser(User user) {
		userDao.addUser(user);
		return "redirect: getAllUsers";
	}
	
	@RequestMapping(value="/updateUser", method=RequestMethod.PUT)
	public String updateUser(User user) {
		userDao.updateUser(user);
		return "redirect: getAllUsers";
	}
	
	/**
	 * 有一个问题，把页面过来的POST请求转换为DELETE请求后，重定向到getAllUsers方法是需要GET方法的，
	 * 所以会匹配不了，报错
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/deleteUserById/{id}", method=RequestMethod.DELETE)
	public String deleteUser(@PathVariable Integer id) {
		if(id != null) {
			userDao.deleteUser(id);
		}
		return "redirect: getAllUsers";
	}
	
	@RequestMapping("/testInterceptor")
	public String testAllInterceptor() {
		log.info("testInterceptor");
		return "success";
	}
	
}
